import React, {useState, useEffect} from 'react';
import  './index.less';
import MyTabbar from '@/components/MyTabbar/MyTabbar';
import { getCates, getItems } from '@/api';
import Items from './components/Items'
export default function Page() {
  const [cates, setCates] = useState<any[]>([]);
  const fetchCates = () => {
    getCates().then(res => {
      if (res.data.code === 0) {
        setCates(res.data.data)
      }
    })
  }
  const [activeIndex, setActiveIndex] = useState(0);

  const [items, setItems] = useState<any[]>([]);
  const fetchItems = () => {
    getItems({
      categoryId: cates[activeIndex].id
    }).then(res => {
      if (res.data.code === 0) {
        setItems(res.data.data.result)
      }
      if (res.data.code === 700) {
        setItems([])
      }
    })
  }

  useEffect(() => {
    if (cates.length === 0) {
      fetchCates();
    } else {
      fetchItems()
    }
  }, [cates, activeIndex])
  return (
    <div className='cate-page'>
      <div className="cate-container">
        <div className="cate-wrap">
          {
            cates.map((cate, index) => (
              <div 
                key={cate.id} 
                onClick={
                  () => {
                    setActiveIndex(index)
                  }
                }
                className={`cate ${index === activeIndex?'active': ''}`}>
                {cate.name}
              </div>
            ))
          }
         
          
        </div>
        <div className="item-wrap">
            <Items items={items}/>
        </div>
      </div>
      <MyTabbar/>
    </div>
  );
}
